package com.example.system.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.system.entity.Params;
import com.example.system.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * <p>
 * Mapper 接口
 * </p>
 *
 * @author hjw
 * @since 2024-01-23
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

    @Delete("DELETE FROM user WHERE id = #{id}")
    int deleteById(User user);

    @Delete("DELETE FROM family_member WHERE cur_user_id = #{curUserID} AND family_member_id = #{familyMemberID};")
    void deleteFamilyMember(@Param("curUserID") Integer curUserID, @Param("familyMemberID") Integer familyMemberID);

    List<User> findPageByUserName(@Param("params") Params params);

    int insertSelective(User user);

    @Select("SELECT * FROM user WHERE username = #{usernmae} LIMIT 1;")
    User findByFullUserName(String username);

    @Select("SELECT * FROM user WHERE id = #{id};")
    User findByUserID(Integer id);

    @Select("SELECT * FROM user WHERE username = #{username} AND password = #{password} LIMIT 1;")
    User findByNameAndPwd(@Param("username") String username, @Param("password") String password);

    @Select("SELECT * FROM user WHERE id = #{id};")
    User findSelfInfoByUserID(Integer id);

    @Select("SELECT \n" +
            "  u2.id AS id,\n" +
            "  u2.username AS username,\n" +
            "  u2.nickname AS nickname\n" +
            "FROM \n" +
            "  family_member fm\n" +
            "JOIN \n" +
            "  user u1 ON fm.cur_user_id = u1.id\n" +
            "JOIN \n" +
            "  user u2 ON fm.family_member_id = u2.id\n" +
            "WHERE \n" +
            "  u1.id = #{id};")
    List<User> findFamilyMemberByUserID(Integer id);

    @Select("SELECT COUNT(*) > 0 FROM user WHERE id = #{userId}")
    boolean existsUserById(@Param("userId") Integer userId);

    @Select("SELECT COUNT(*) > 0 FROM family_member " +
            "WHERE cur_user_id = #{curUserId} AND family_member_id = #{familyMemberId};")
    boolean existsFamilyMemberPair(@Param("curUserId") Integer curUserId,
                                   @Param("familyMemberId") Integer familyMemberId);

    @Insert("INSERT INTO family_member VALUES (#{curUserID}, #{familyMemberID});")
    void addNewFamilyMember(@Param("curUserID") Integer curUserID, @Param("familyMemberID") Integer familyMemberID);
}
